package de.preissler.jointest;

import java.util.List;

import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.HSuperColumn;
import me.prettyprint.hector.api.beans.SuperRow;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.query.RangeSuperSlicesQuery;
import me.prettyprint.hector.api.query.SubSliceQuery;

public class DAXCalc implements DAX
{
	private static final String DAX = "DAX";
	private static final String QUOTES = "Quotes";
	private static final String ISIN = "DE0008469008";
	private static final String CLOSE = "close";

	public void getDAXValues(List<String> dates, Keyspace keyspace, double[] result)
	{
		//Daten zur DAX Berechnung abrufen
		RangeSuperSlicesQuery<String, String, String, Double> daxQuery = HFactory.createRangeSuperSlicesQuery(keyspace, SS, SS, SS, DS);
		daxQuery.setColumnFamily(DAX);
		daxQuery.setKeys(dates.get(dates.size()-1), dates.get(0));
		daxQuery.setRange(null, null, false, Integer.MAX_VALUE);
		List<SuperRow<String, String, String, Double>> daxResult = daxQuery.execute().get().getList();
		
		
		for(int i = 0; i < daxResult.size(); i++)
		{
			double divident = 0.0;
			double divisor = 0.0;
			double kt = 0.0;
			double base = 0.0;
			for(HSuperColumn<String, String, Double> sc : daxResult.get(i).getSuperSlice().getSuperColumns())
			{
				if(!sc.getName().equals(ISIN))
				{
					double close = getClose(sc.getName(), daxResult.get(i).getKey(), keyspace);
					double pi0 = sc.get(4).getValue();
					if(pi0 == -1.0)
						pi0 = 1.0;
					double qi0 = sc.get(1).getValue();
					if(qi0 == -1.0)
						qi0 = 1.0;
					double qit = sc.get(0).getValue();
					if(qit == -1.0)
						qit = 1.0;
					double ffit = sc.get(3).getValue();
					if(ffit == -1.0)
						ffit = 1.0;
					double ci = sc.get(2).getValue();
					if(ci == -1.0)
						ci = 1.0;
					
					divident = divident + (close*qit*ffit*ci);
					divisor = divisor + (pi0 * qi0);
				}
				else
				{
					kt = sc.get(0).getValue();
					base = sc.get(1).getValue();
				}
			}
			result[daxResult.size()-1-i] = kt * (divident/divisor) * base;
		}
	}
	
	public double getClose(String isin, String date, Keyspace keyspace)
	{
		SubSliceQuery<String, String, String, Double> query = HFactory.createSubSliceQuery(keyspace, SS, SS, SS, DS);
		query.setColumnFamily(QUOTES);
		query.setKey(isin);
		query.setSuperColumn(date);
		query.setColumnNames(CLOSE);
		
		return query.execute().get().getColumnByName(CLOSE).getValue();
	}

}
